package cn.iocoder.yudao.framework.web.core.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

/**
 * Created by Administrator on 2016/11/11.
 */
public class ServletUtils {

    private static final Logger LOG = LoggerFactory.getLogger(ServletUtils.class);

    public static String getRemoteIP(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * Servlet3没有提供直接获取文件名的方法,需要从请求头中解析出来
     * 获取请求头，请求头的格式：form-data; name="file"; filename="snmp4j--api.zip"
     * 根据请求头解析出文件名
     * 请求头的格式：火狐和google浏览器下：form-data; name="file"; filename="snmp4j--api.zip"
     * IE浏览器下：form-data; name="file"; filename="E:\snmp4j--api.zip"
     */
    public static String getFileName(Part part) {

        String header = part.getHeader("content-disposition");

        if (StringUtils.isBlank(header)) {
            return null;
        }
        /*
          String[] tempArr1 = header.split(";");代码执行完之后，在不同的浏览器下，tempArr1数组里面的内容稍有区别
          火狐或者google浏览器下：tempArr1={form-data,name="file",filename="snmp4j--api.zip"}
          IE浏览器下：tempArr1={form-data,name="file",filename="E:\snmp4j--api.zip"}
         */
        String[] tempArr1 = header.split(";");
        if (tempArr1.length < 3) {
            return null;
        }
        /*
         火狐或者google浏览器下：tempArr2={filename,"snmp4j--api.zip"}
         IE浏览器下：tempArr2={filename,"E:\snmp4j--api.zip"}
         */
        String[] tempArr2 = tempArr1[2].split("=");
        if (tempArr2.length < 2) {
            return null;
        }
        //获取文件名，兼容各种浏览器的写法
        return tempArr2[1].substring(tempArr2[1].lastIndexOf("\\") + 1).replaceAll("\"", "");
    }

    public static String getCookieValue(HttpServletRequest req, String cookieKey) {
        if (req == null || StringUtils.isBlank(cookieKey)) {
            return null;
        }
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookieKey.trim().equalsIgnoreCase(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }


    public static void addCookie(HttpServletResponse resp, String key, String value, String domain, String path, Integer maxAge) {
        if (resp == null || StringUtils.isBlank(key)) {
            return;
        }
        Cookie cookie = new Cookie(key, value);
        if (StringUtils.isNotBlank(domain)) {
            cookie.setDomain(domain);
        }
        if (StringUtils.isNotBlank(path)) {
            cookie.setPath(path);
        } else {
            cookie.setPath("/");
        }
        if (maxAge != null) {
            cookie.setMaxAge(maxAge);
        }
        resp.addCookie(cookie);
    }

    public static void removeCookie(HttpServletResponse resp, String key) {
        addCookie(resp, key, null, null, null, 0);
    }

    public static void clearSession(HttpServletRequest req) {
        try {
            req.getSession().invalidate();
        } catch (Exception ignored) {
        }
    }


}
